package com.biscuit.page.basicservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.biscuit.page.basicservice.conf.config.AlipayConfig;
import com.biscuit.page.basicservice.utils.CommonUtil;
import com.biscuit.page.basicservice.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author biscuit
 * @create 2024年08月05日 12:11
 */
@Slf4j
@Service
public class PaymentService {

    @Resource
    private AlipayConfig alipayConfig;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    public void alipay(BigDecimal amount, HttpServletResponse httpResponse) {
        // 创建阿里支付客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, this.alipayConfig.getConfigurationProperties().getAppId(),
                this.alipayConfig.getConfigurationProperties().getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getConfigurationProperties().getAlipayPublicKey(), SIGN_TYPE);

        // 支付请求对象中需要的业务参数
        Map<String, Object> bizContentMap = new HashMap<>();
        bizContentMap.put("out_trade_no", CommonUtil.getUUID()); // 支付唯一订单编号
        bizContentMap.put("total_amount", amount); // 支付金额
        bizContentMap.put("subject", "测试支付");  // 支付标题
        bizContentMap.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 支付创建
        bizContentMap.put("time_expire", DateUtil.format(cn.hutool.core.date.DateUtil.offsetMinute(new Date(), 30), "yyyy-MM-dd HH:mm:ss")); // 支付超时时间

        // 创建支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(this.alipayConfig.getConfigurationProperties().getNotifyUrl());
        request.setBizContent(JSON.toJSONString(bizContentMap));

        String form = "";
        try {
            // 请求支付生成支付页面
            form = alipayClient.pageExecute(request).getBody();


            httpResponse.setContentType("text/html;charset=" + CHARSET);
            // 直接将完整的表单html输出到页面
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public void alipayNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单为已支付

            }
        }
    }
}
